<template>
  <div class="zd-lifeMessenger wrap-table">
    <el-tabs v-model="periodModel" type="card">
      <el-tab-pane label="消息设置" name="1">
        <el-form
          ref="form"
          :model="searchData"
          label-width="120px"
          class="clearfix flex-div"
        >
          <el-form-item
            label="创建日期"
            label-width="70px"
            style="width: 340px"
          >
            <div class="block">
              <el-date-picker
                v-model="timeDate"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="发送状态" style="width: 220px">
            <el-select v-model="searchData.isSend" placeholder="请选择">
              <el-option label="已发送" value="1"></el-option>
              <el-option label="未发送" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题">
            <el-input
              v-model="searchData.title"
              placeholder="请输入标题"
              clearable
            >
            </el-input>
          </el-form-item>
          <!-- 操作区域 -->
          <div class="flex-r-but">
            <el-button @click="queryHandler" class="mg-lr-20 pd-bt"
              >查询</el-button
            >
            <el-button
              type="primary"
              @click="addHandler"
              class="pull-right pd-bt"
              >添加</el-button
            >
          </div>
        </el-form>
        <!-- table 展示  -->
        <template>
          <el-table
            :data="table.tableData"
            border
            empty-text="当前列表为空"
            v-loading="loading"
            element-loading-text="加载中"
            style="width: 100%"
          >
            <el-table-column
              prop="CreateTime"
              label="创建时间"
              min-width="200"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="Title"
              label="消息标题"
              min-width="200"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="Period"
              label="适用人群"
              min-width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="SendType"
              label="推送类型"
              min-width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="OpName"
              label="创建人"
              min-width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="IsSend"
              label="发送状态"
              min-width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.IsSend != '已发送'"
                  @click="handleClick(scope.row)"
                  type="text"
                  size="small"
                >
                  修改
                </el-button>
                <el-button
                  type="text"
                  v-if="scope.row.IsSend != '已发送'"
                  size="small"
                  @click="deleteHandler(scope.$index, scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <!--分页-->
        <div class="block mg-20-auto pagination-fixed">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="pageId"
            :page-sizes="[10, 20, 30, 40, 80, 100, 200, 500]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="发送记录" name="2">
        <el-form
          ref="form"
          :model="searchData2"
          label-width="120px"
          class="clearfix flex-div"
        >
          <el-form-item
            label="发送日期"
            label-width="70px"
            style="width: 340px"
          >
            <div class="block">
              <el-date-picker
                v-model="timeDate2"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="研究编号">
            <el-input
              v-model="searchData2.womanId"
              placeholder="请输入研究编号"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="阅读状态" style="width: 220px" >
            <el-select v-model="searchData2.isRead" placeholder="请选择" clearable>
              <el-option label="已阅读" value="1"></el-option>
              <el-option label="未阅读" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题">
            <el-input
              v-model="searchData2.title"
              placeholder="请输入标题"
              clearable
            >
            </el-input>
          </el-form-item>
          <!-- 操作区域 -->
          <div class="flex-r-but">
            <el-button @click="research" class="mg-lr-20 pd-bt"
              >查询</el-button
            >
          </div>
        </el-form>
        <!-- table 展示  -->
        <template>
          <el-table
            :data="tableData"
            border
            empty-text="当前列表为空"
            v-loading="loading"
            element-loading-text="加载中"
            style="width: 100%"
          >
            <el-table-column
              prop="SendTime"
              label="发送时间"
              min-width="200"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="Surname"
              label="姓名首字母"
              min-width="100"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="ResearchNo"
              label="研究编号"
              min-width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="SendType"
              label="消息类型"
              min-width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="MessageTitle"
              label="消息标题"
              min-width="220"
              :show-overflow-tooltip="true"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="IsSend"
              label="发送状态"
              min-width="100"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="IsRead"
              label="阅读状态"
              min-width="100"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="IsSend"
              label="阅读时间"
              min-width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="IsSend"
              label="发送者"
              min-width="120"
              align="center"
            >
            </el-table-column>
          </el-table>
        </template>
        <!--分页-->
        <div class="block mg-20-auto pagination-fixed">
          <el-pagination
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
            :current-page.sync="pageId2"
            :page-sizes="[10, 20, 30, 40, 80, 100, 200, 500]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total2"
          ></el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 查询区域 -->

    <!-- 对话框 -->

    <el-dialog
      :title="dialogData.title"
      :close-on-click-modal="false"
      :visible.sync="dialogData.isShow"
      @close="closeDialog()"
      :append-to-body="true"
      top="0"
    >
      <!-- rules="rules" -->
      <el-form
        :model="formData"
        label-position="left"
        :rules="rules"
        ref="addressForm"
      >
        <div class="flex-div">
          <el-form-item
            label="研究阶段"
            style="width: 300px"
            label-width="100px"
          >
            <el-select v-model="formData.Period" placeholder="请选择">
              <el-option label="" value=""></el-option>
              <el-option label="孕前期" value="1"></el-option>
              <el-option label="怀孕期" value="2"></el-option>
              <el-option label="育儿期" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="
              formData.Period == '1'
                ? '备孕天数'
                : formData.Period == '2'
                ? '孕周'
                : '宝宝月龄'
            "
            style="margin-left: 50px"
            label-width="100px"
            prop="ArticleTitle"
          >
            <el-input
              size="small"
              style="width: 80px"
              v-model="formData.StartTimespan"
            ></el-input>
            ~
            <el-input
              size="small"
              style="width: 80px"
              v-model="formData.EndTimespan"
            ></el-input>
          </el-form-item>
        </div>
        <div class="flex-div">
          <el-form-item label="研究组别" label-width="100px">
            <el-select v-model="formData.GroupType" placeholder="请选择">
              <el-option
                v-for="item in studyOptions"
                :key="item.value"
                :label="item.Name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="干预强度"
            label-width="100px"
            v-if="formData.GroupType == '1'"
            style="margin-left: 50px"
          >
            <el-select
              v-model="formData.IntensityOfIntervention"
              placeholder="请选择"
            >
              <el-option
                v-for="item in AAstudyOptions"
                :key="item.value"
                :label="item.Name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="消息标题" label-width="100px" prop="Title">
          <el-input v-model="formData.Title"></el-input>
        </el-form-item>
         <el-form-item label="消息摘要" label-width="100px" >
          <el-input v-model="formData.MessageSubject"></el-input>
        </el-form-item>
        <el-form-item label="消息正文" prop="MessageContent">
          <Editor
            class="editor"
            v-if="hackReset"
            @onchangeEditor="onchangeEditor"
            tbSel="editor"
            :editorContent="formData.MessageContent"
          />
        </el-form-item>
        <el-form-item label="发送类型" label-width="100px" prop="SendType">
          <el-select v-model="formData.SendType" placeholder="请选择">
            <el-option label="定时发送" value="1"></el-option>
            <el-option label="立即发送" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogData.isShow = false">取 消</el-button>
        <el-button
          type="primary"
          @click="saveHandler"
          v-loading.fullscreen.lock="fullscreenLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Editor from "@/components/editor/list";
import { mapGetters } from "vuex";
import { DIC_PERIODB } from "@/utils/localDic";
const ArticleContent = (rule, value, callback) => {
  if (
    !value ||
    (value.indexOf("<p><br></p>") > -1 &&
      value.indexOf("</p><p><br></p>") == -1)
  ) {
    return callback(new Error("必填项"));
  } else {
    callback();
  }
};

export default {
  name: "lifeMessenger",

  components: {
    Editor,
  },

  data() {
    return {
      fullscreenLoading: false,
      tableData:[],
      pageId: 1,
      total: null,
      loading: true,
      pageSize: 10,
      pageId2: 1,
      total2: null,
      loading2: true,
      pageSize2: 10,
      searchData2:{
        isRead:"",
        title:""
      },
      timeDate: [],
      timeDate2: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      periodModel: "1",
      hackReset: false,
      Period: "1", //记录数值
      searchData: {
        // 查询from
        isSend: "",
        title: "",
      },
      loading: true,
      table: {
        //table  数据
        tableData: [],
        loading: false, //table  loading
      },
      dialogData: {
        // 弹窗数据
        title: "添加信使信息",
        isShow: false,
      },

      formData: {
        //弹窗数据
        Title: "",
        GroupType: "1",
        SendType: "1",
        Period: "",
        IntensityOfIntervention:"",
        MessageContent: "",
      },
      rules: {
        // 表单验证
        Title: [{ required: true, message: "必填项", trigger: "blur" }],
        MessageContent: [
          { required: true, validator: ArticleContent, trigger: "blur" },
        ],
        SendType: [{ required: true, message: "必填项", trigger: "blur" }],
      },
      GroupTypeFilter(row, column, cellValue, index) {
        return cellValue == "1" ? "A" : "B";
      },
      studyOptions: [
        //  研究阶段数据
        {
          Name: "",
          value: "",
        },
        {
          Name: "A",
          value: "1",
        },
        {
          Name: "B",
          value: "2",
        },
      ],
      AAstudyOptions: [
        //  研究阶段数据
        {
          Name: "",
          value: "",
        },
        {
          Name: "AA",
          value: "1",
        },
        {
          Name: "A",
          value: "2",
        },
      ],
      applicableOptiona: DIC_PERIODB,
      contents: "",
    };
  },
  computed: {
    ...mapGetters(["resechObj", "RoleGroup", "token", "UserDic"]),
  },
  watch: {
    periodModel: function (value) {
      value == '1' ?  this.getList() :  this.getList2();
    },
  },
  mounted() {
    let that = this;
    let now = new Date();
    let nowTime = now.getTime();
    let day = now.getDay();
    if (day == 0) {
      //西方从周日算为第一天    2018/10/28
      day = 7;
    }
    let oneDayLong = 24 * 60 * 60 * 1000;
    let MondayTime = nowTime - (day - 1) * oneDayLong;
    let SundayTime = nowTime + (7 - day) * oneDayLong;
    let monday = dateForm(new Date(MondayTime));
    let sunday = dateForm(new Date(SundayTime));
    that.timeDate = ['2022-01-01', sunday]; //初始化时间范围
    that.timeDate2 = [monday, sunday];
    this.getList();
  },
  methods: {
    handleSizeChange(val) {
      //条数改变
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      //页数改变
      this.pageId = val;
      this.getList();
    },
    handleSizeChange2(val) {
      //条数改变
      this.pageSize2 = val;
      this.getList2();
    },
    handleCurrentChange2(val) {
      //页数改变
      this.pageId2 = val;
      this.getList2();
    },
    deleData() {
      // 每次点开之前 清空数据
      this.formData = {
         Title: "",
        GroupType: "1",
        SendType: "1",
        Period: "",
        IntensityOfIntervention:"",
        MessageContent: "",
      };
      this.aa = {
        MessageContent: "",
      };
    },

    closeDialog() {
      //监听窗口关闭后清掉验证
      this.$refs["addressForm"].resetFields();
    },

    getList() {
      // 获取首页数据
      this.table.tableData = [];
      this.laoding = true;
      this.service({
        url: "Message/GetMessageTemplateList",
        method: "get",
        params: {
          ...this.searchData,
          pageCount: this.pageId - 1,
          pageSize: this.pageSize,
          startDate: this.timeDate ? this.timeDate[0] : "",
          endDate: this.timeDate ? this.timeDate[1] : "",
        },
      })
        .then((res) => {
          if (res.isSuccess) {
            this.table.tableData = res.dtData;
            this.total = parseInt(res.dtData[0].TotalCount);
          }
          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
          console.log(error);
        });
    },
    getList2() {
      // 获取首页数据
      this.laoding2 = true;
      this.service({
        url: "Message/GetMessageRecord",
        method: "get",
        params: {
          ...this.searchData2,
          pageCount: this.pageId2 - 1,
          pageSize: this.pageSize2,
          startDate: this.timeDate2 ? this.timeDate2[0] : "",
          endDate: this.timeDate2 ? this.timeDate2[1] : "",
        },
      })
        .then((res) => {
          if (res.isSuccess) {
            console.log(res)
            this.tableData = res.dtData;
            this.total2 = parseInt(res.dtData[0].TotalCount);
          }
          this.loading2 = false;
        })
        .catch((error) => {
          this.loading2 = false;
          console.log(error);
        });
    },
    queryHandler() {
      // 用户点击查询事件
      this.pageId=1;
      this.pageSize=10;
      this.getList();
    },
    research(){
      this.pageId2=1;
      this.pageSize2=10;
      this.getList2();
    },
    addHandler() {
      //添加事件
      this.deleData();
      this.dialogData.isShow = true;
      this.dialogData.title = "添加信使信息";
      this.hackReset = false;
      this.$nextTick(() => {
        this.hackReset = true;
      });
    },

    saveHandler() {
      // 弹窗数据保存
      this.formData.MessageContent = JSON.parse(JSON.stringify(this.contents));
      this.$refs.addressForm.validate((valid) => {
        if (valid) {
          this.fullscreenLoading = true;
          this.service({
            url: "Message/SaveMessageTemplate",
            method: "post",
            data: {
              ...this.formData,
              OpId: JSON.parse(this.UserDic).SYS_ID,
              OpName: JSON.parse(this.UserDic).UserCode,
            },
          }).then((res) => {
            this.fullscreenLoading = false;
            this.dialogData.isShow = false;
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.getList();
          }).catch(e =>{
             this.dialogData.isShow = false;
            this.fullscreenLoading = false;
          })
        } else {
          this.$message({
            message: "验证失败",
            type: "warning",
          });
        }
      });
    },
    handleClick(data) {
      // 数据修改

      this.dialogData.isShow = true;
      this.dialogData.title = "编辑消息";
      this.hackReset = false;
      this.$nextTick(() => {
        this.hackReset = true;
      });
      this.service({
        url: "Message/GetMessageTemplate",
        params: {
          id: data.SYS_ID,
        },
        method: "get",
      }).then((res) => {
        this.formData = { ...res.dtData[0] };
        this.contents = this.formData.MessageContent;
      });
    },

    deleteHandler(index, row) {
      // 数据删除
      this.$confirm("是否删除本事项？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.service({
          url: "Message/DeleteMessageTemplate",
          data: { ...row },
          method: "post",
        }).then((res) => {
          if (res.isSuccess) {
            this.$message({
              message: res.msg,
              type: "success",
            });
            this.getList();
          }
        });
      });
    },
    onchangeEditor(a) {
      // 组件回调
      this.contents = a;
    },
  },
};
function dateForm(data) {
  return (
    new Date(data).getFullYear() +
    "-" +
    addZero(new Date(data).getMonth() + 1) +
    "-" +
    addZero(new Date(data).getDate())
  );
}
function addZero(s) {
  return s < 10 ? "0" + s : s;
}
</script>

<style  lang= "scss" >
.el-dialog__body {
  max-height: 400px;
  overflow: auto;
}
.editor {
  margin-top: 40px;
}
.pd-bt {
  padding: 12px 30px;
}
.pagination-fixed {
  position: static;
}
.arrow-top {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  width: 8px;
  height: 8px;
  border: 1px solid #409eff;
  border-width: 1px 0 0 1px;
  transform: rotate(45deg) translateY(-50%);
}
.arrow-top:before {
  content: "";
  position: absolute;
  height: 1px;
  width: 12px;
  background-color: #409eff;
  left: 0;
  top: -1px;
  transform: rotate(45deg);
  transform-origin: 0 0;
}

.arrow-bottom {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  width: 8px;
  height: 8px;
  border: 1px solid #409eff;
  border-width: 0 1px 1px 0;
  transform: rotate(45deg);
}
.arrow-bottom:before {
  content: "";
  position: absolute;
  height: 1px;
  width: 12px;
  background-color: #409eff;
  right: 0;
  bottom: 0;
  transform: rotate(45deg);
  transform-origin: 100% 0;
}
</style>


